php associative array join key values

126

If you want to implode an array as key-value pairs, this method comes in handy.
The third parameter is the symbol to be used between key and value.

<?php
function mapped_implode($glue, $array, $symbol = '=') {
    return implode($glue, array_map(
            function($k, $v) use($symbol) {
                return $k . $symbol . $v;
            },
            array_keys($array),
            array_values($array)
            )
        );
}

$arr = [
    'x'=> 5,
    'y'=> 7,
    'z'=> 99,
    'hello' => 'World',
    7 => 'Foo',
];

echo mapped_implode(', ', $arr, ' is ');

// output: x is 5, y is 7, z is 99, hello is World, 7 is Foo

?>

Comments

Submit
0 Comments